#include <my_hander.h>

int main()
{
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    
    // 客户端sockaddr_in结构体里存要访问服务端的网络类型、端口号和ip地址
    // 注意是存服务端的！
    struct sockaddr_in s;
    s.sin_family = AF_INET;
    s.sin_port = htons(30003);
    s.sin_addr.s_addr = inet_addr("127.0.0.1");
    int reuse = 1;
	// SO_REUSEADDR是个布尔类型，定义一个int表示将其改为1
    setsockopt(server_fd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));

    printf("请输入您的用户名：\n");
    char name_buf[20];
    scanf(" %s", name_buf);
    int name_len = strlen(name_buf);

    // 通过connect函数连接服务端
    int ret = connect(server_fd, (struct sockaddr *)&s, sizeof(s));
    ERROR_CHECK(ret, -1, "connect");
    printf("您已连接至服务器！\n");
    printf("输入 .r 可查看当前在线用户及其序号\n");
    printf("输入 pchat + 序号 可私聊该序号用户，例：pchat5nihao\n");
    printf("30秒未发言会被踢出！\n");
    printf("\n");
    send(server_fd, &name_len, sizeof(int), 0);
    send(server_fd, name_buf, name_len, 0);

    char buf[1024] = {0};
    fd_set rdset;
    
    while(1)
    {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(server_fd, &rdset);
        select(server_fd + 1, &rdset, NULL, NULL, NULL);
        
        if(FD_ISSET(STDIN_FILENO,&rdset))
        {
            bzero(buf, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            if(ret == 0)
            {
                printf("未输入任何字符，已断开链接！\n");
                break;
            }
            send(server_fd, buf, strlen(buf) -1 ,0);
        }
        else if(FD_ISSET(server_fd,&rdset))
        {
            bzero(buf, sizeof(buf));
            int ret;
            ret = recv(server_fd, buf, sizeof(buf), 0);
            if (ret == 0)
            {
                printf("服务器已断开链接！\n");
                break;
            }
            printf("%s\n", buf);
        }
    }
    

    close(server_fd);
  
    return 0;
}

